package cn.org.donald.framework.util;

import cn.org.donald.framework.property.AuthorizationProperties;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import cn.org.donald.framework.pojo.dto.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ： Donald
 * @date ： 2020/10/19 00:43
 * @description： JWT工具类
 */
@Component
public class JwtUtil {



    public static final String TOKEN_NAME = "token";

    public static final String EXPIRE_TIME_NAME = "expireTime";


    @Autowired
    private AuthorizationProperties authorizationProperties;



    @Bean
    public void setExpireTime() {
        EXPIRE_TIME = TimeUtil.getMinuteMillis(authorizationProperties.getTimeout());
    }

    private static Long EXPIRE_TIME;
    //密钥用于生成token的签名
    private static final String SIGN = "!1qaz.(";

    private static final String ISSUER = "Donald";




    public static String getToken(String userId, int timeout) {
        Date date = new Date(System.currentTimeMillis() + TimeUtil.getMinuteMillis(timeout));
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(ISSUER)
                .withExpiresAt(date)
                .withClaim("userId",userId);
        return builder.sign(Algorithm.HMAC256(SIGN));
    }


    /**
     * 根据LoginUser(用户id和用户名)生成jwt
     * @param loginUser
     * @return Map
     */
    public static Map<String,Object> getLoginToken(LoginUser loginUser){
        Date date = new Date(System.currentTimeMillis() + TimeUtil.getMinuteMillis(EXPIRE_TIME));
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(ISSUER)
                .withExpiresAt(date)
                .withClaim("userId",loginUser.getUserId())
                .withClaim("userName",loginUser.getUserName());
        String token = builder.sign(Algorithm.HMAC256(SIGN));
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put(TOKEN_NAME,token);
        tokenMap.put(EXPIRE_TIME_NAME,EXPIRE_TIME);
        return tokenMap;
    }

    /**
     * 解码token
     * @param token jwt
     * @return DecodedJWT
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }
}

